package com.click.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        log.error("业务异常: {}", e.getMessage(), e);
        return Result.error(e.getErrorCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Result<?> handleValidationException(Exception e) {
        String message = "参数校验失败";
        if (e instanceof MethodArgumentNotValidException) {
            var fieldError = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError();
            message = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        } else if (e instanceof BindException) {
            var fieldError = ((BindException) e).getBindingResult().getFieldError();
            message = fieldError != null ? fieldError.getDefaultMessage() : "参数校验失败";
        }
        log.error("参数校验异常: {}", message);
        return Result.error(ErrorCode.PARAM_ERROR, message);
    }
    
    /**
     * 处理参数校验异常（单个参数）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e) {
        String message = e.getConstraintViolations().iterator().next().getMessage();
        log.error("参数校验异常: {}", message);
        return Result.error(ErrorCode.PARAM_ERROR, message);
    }
    
    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return Result.error(ErrorCode.INTERNAL_ERROR);
    }
}